package com.htx.zqs.blesmartmask.ui.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.data.BleDevice;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.google.gson.Gson;
import com.htx.zqs.blesmartmask.MyApplication;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.NotifyData;
import com.htx.zqs.blesmartmask.broadcastreceiver.NetworkReceiver;
import com.htx.zqs.blesmartmask.custom.AutoScrollTextView;
import com.htx.zqs.blesmartmask.eventbus.MessageEvent;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.ui.fragment.DeviceNewFragment;
import com.htx.zqs.blesmartmask.ui.fragment.HomeFragment;
import com.htx.zqs.blesmartmask.ui.fragment.OrderFragment;
import com.htx.zqs.blesmartmask.ui.fragment.ThirdFragment;
import com.htx.zqs.blesmartmask.utils.AlertUtils;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.Constants;
import com.htx.zqs.blesmartmask.utils.Logger;
import com.htx.zqs.blesmartmask.utils.MySpUtils;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;
import com.htx.zqs.blesmartmask.utils.Tools;
import com.htx.zqs.blesmartmask.utils.UpNetWaterData;
import com.htx.zqs.blesmartmask.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.bmob.v3.Bmob;
import timber.log.Timber;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private static final int REQUEST_ENABLE_BT = 101;
    @InjectView(R.id.main_fragment_container)
    public FrameLayout mainFragmentContainer;
    @InjectView(R.id.main_bottome_switcher_container)
    LinearLayout mainBottomeSwitcherContainer;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.showMarquee)
    AutoScrollTextView mShowMarquee;
    String[] titles;
    @InjectView(R.id.ib_menu)
    TextView ibMenu;
    private HomeFragment homeFragment;
    private DeviceNewFragment deviceFragment;

    private OrderFragment orderFragment;
    private BluetoothAdapter bluetoothAdapter;

    private int position;
    private long exitTime = 0;
    private ThirdFragment thirdFragment;
    private NetworkReceiver mNetworkReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        ButterKnife.inject(this);
        Logger.d("应用版本：" + Tools.getVersion(this));
        initDate();

        //提供4个fragment供底部选项卡的切换
        bluetoothAdapter = BlEUtile.getBleAdapter();
        initFragment(savedInstanceState);
        initBmob();
        //初始化底部四个条目的点击事件 biaoti
        initClick();
        //默认触发索引位置0的点击事件,代表默认选中首页
        goToFragment(0);
        startReceiver();
        if (!Utils.checkNotifySetting(this)) {
            AlertUtils.showAlertDialog(activity, getString(R.string.open_notification_hint),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Utils.openPermissionSetting(activity);
                        }
                    });
        }
        ibMenu.setVisibility(View.VISIBLE);
        ibMenu.setText(R.string.instructions);
    }

    private void startReceiver() {
        mNetworkReceiver = new NetworkReceiver();
        //在代码中实现动态注册的方式
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetworkReceiver, filter);
    }

    //  初始化数据
    private void initDate() {
        titles = new String[]{getResources().getString(R.string.main_btn_text_first),
                getResources().getString(R.string.main_btn_text_second),
                getResources().getString(R.string.main_btn_text_third),
                getResources().getString(R.string.main_btn_text_fourth)};
        isNeedNotify();
        mShowMarquee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mShowMarquee.setVisibility(View.GONE);
            }
        });
    }


    private void isNeedNotify() {
        OkhttpUtils okhttpUtils = new OkhttpUtils(this, Contants.NOTIFY, new OkListener() {
            @Override
            public void onSuccess(int requestCode, String string) {
                Log.e("main", "initBLE: " + string + "========");
                showNotify(string);
            }

            @Override
            public void onError(int requestCode, IOException e) {
                Log.e("main", "initBLE: " + e + "========");
            }
        });

        if (BlEUtile.isNetworkConnected(this)) {
            // okhttpUtils.get(Contants.NOTIFY, Contants.BASE_URL + NOTIFY);
            okhttpUtils.get(Contants.NOTIFY, Contants.BASE_URL + "importnotices.link?id=1");
        } else {
            String json = (String) SPUtil.get(MainActivity.this, "notify", "", "notify");
            if (!TextUtils.isEmpty(json)) {
                showNotify(json);
            }
        }


    }

    private void showNotify(String string) {
        Gson gson = new Gson();
        NotifyData notifyData = gson.fromJson(string, NotifyData.class);
        NotifyData.DataBean dataBean = notifyData.getData();
        SPUtil.put(MainActivity.this, "notify", string, "notify");
        String notice = dataBean.getNotice();
        String isBool = dataBean.getBool();
        if ("true".equals(isBool)) {
            mShowMarquee.setVisibility(View.VISIBLE);
            mShowMarquee.setText(notice);
            mShowMarquee.setMarqueeRepeatLimit(-1);
        } else {
            mShowMarquee.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }


    @Override
    public boolean isFinishing() {
        return super.isFinishing();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("position", position);
        super.onSaveInstanceState(outState);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        initBLE();
    }

    private void initFragment(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            homeFragment = (HomeFragment) fragmentManager.findFragmentByTag("homeFragment");
            deviceFragment = (DeviceNewFragment) fragmentManager.findFragmentByTag("deviceFragment");
            //chartFragment = (ChartFragment) fragmentManager.findFragmentByTag("chartFragment");
            //    userFragment = (UserFragment) fragmentManager.findFragmentByTag("userFragment");
            orderFragment = (OrderFragment) fragmentManager.findFragmentByTag("orderFragment");
            thirdFragment = (ThirdFragment) fragmentManager.findFragmentByTag("thirdFragment");

        } else {
            changFragment(0);
        }
    }

    private void initBLE() {   // 开启蓝牙

        if (bluetoothAdapter != null) {
            if (!bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.enable();
                Toast.makeText(this, getResources().getString(R.string.main_bluetooth_on), Toast.LENGTH_SHORT).show();
//                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        } else {
            tvTitle.setText(getResources().getString(R.string.main_bluetooth_nosupport));
            Log.i("main", "initBLE: " + 444);
        }
//        boolean b = BlEUtile.checkLocatoinPermission(this);
//        if (b){
//            Toast.makeText(this,"nihaoma",Toast.LENGTH_LONG).show();
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("=========main====" + resultCode, "=======162=");
        Log.e("====", data + "===");

        if (requestCode == REQUEST_ENABLE_BT) {
            Toast.makeText(this, getResources().getString(R.string.main_bluetooth_on), Toast.LENGTH_SHORT).show();
            Log.e("=========main====" + requestCode, "=======170");
        }
        if (requestCode == 430 && data != null) {
            //获取选择器返回的数据
            ArrayList<String> images = data.getStringArrayListExtra(
                    ImageSelectorUtils.SELECT_RESULT);
            Log.e("=========main====" + requestCode, "=======170");
            // 发布事件
            EventBus.getDefault().post(new MessageEvent(images.get(0), 550));
        }
    }

    public void goToBluetooth() {
        new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.blebroadcast_title))
                .setMessage(getResources().getString(R.string.start_message))
                .setNegativeButton(getResources().getString(R.string.cancle), null)
                .setPositiveButton(getResources().getString(R.string.main_bluetooth_go), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        goToFragment(1);
                        sendBroadcastTevice();
                    }
                })
                .show();
    }

    public void sendBroadcastTevice() {
        Intent intent = new Intent("scan");
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    public void goToFragment(int index) {
        View childAt = mainBottomeSwitcherContainer.getChildAt(index);
        MainActivity.this.onClick(childAt);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeUIEvent(MessageEvent messageEvent) {
        if (messageEvent.getCode() == 600) {
            EventBus.clearCaches();
            goToFragment(0);
        } else if (messageEvent.getCode() == Constants.EVENT_UP_WATER_DATA) {
            //上传油水数据
            UpNetWaterData.create(activity).cacheUp();
        } else if (messageEvent.getCode() == Constants.EVENT_UP_DEVICE_INFO) {
            //上传设备使用情况
            upDeviceInfo();
        }
    }

    private void upDeviceInfo() {
        OkhttpUtils okhttpUtils = new OkhttpUtils(activity, Contants.BLUE_TIME, new OkListener() {
            @Override
            public void onSuccess(int requestCode, String string) {
                Timber.e("上传设备使用情况成功");
            }

            @Override
            public void onError(int requestCode, IOException e) {

            }
        });
        BleDevice bleDevice = Utils.getFirstDevice();
        if (bleDevice == null) return;
        HashMap map = new HashMap();
        map.put("address", bleDevice.getMac());
        map.put("numberlong", String.valueOf(MySpUtils.getInt(MySpUtils.KEY_DEVICE_USE_NUM, -1)));//使用次数
        map.put("min", String.valueOf(MySpUtils.getInt(MySpUtils.KEY_DEVICE_USE_TIME, -1)));//使用时间
        okhttpUtils.postForm(Contants.BLUE_TIME, Contants.URL_BLUE_TIME, map);
    }

    private void initBmob() {
        Bmob.initialize(this,
                "8b6e7296daa671fe7a083e528701526a");
    }

    private void initClick() {
        //1.获取线性布局内部的所有孩子节点总数
        int childCount = mainBottomeSwitcherContainer.getChildCount();
        for (int i = 0; i < childCount; i++) {
            FrameLayout framelayout = (FrameLayout) mainBottomeSwitcherContainer.getChildAt(i);
            framelayout.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        //根据点中的view对象,获取此view对象在父容器中的位置
        int indexOfChild = mainBottomeSwitcherContainer.indexOfChild(v);
        //1.切换选中v内部的ImageView和textView颜色为红色,选中,不可用
        changUi(indexOfChild);
        changFragment(indexOfChild);
        Log.i("ble", "changFragment: " + 999);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (MyApplication.bluetoothGatt != null) {
            MyApplication.bluetoothGatt.close();
        }
        MyApplication.meBluetoothGattCallback = null;
        MyApplication.isConnected = false;
        BlEUtile.setNull();
        //关闭蓝牙
        //  bluetoothAdapter.disable();
        EventBus.getDefault().unregister(this);
        if (mNetworkReceiver != null) {
            unregisterReceiver(mNetworkReceiver);
        }
    }

    /**
     * @param indexOfChild 根据索引切换fragment
     */
    private void changFragment(int indexOfChild) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideFragment(fragmentTransaction);
        position = indexOfChild;
        switch (indexOfChild) {
            case 0:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    fragmentTransaction.add(R.id.main_fragment_container, homeFragment, "homeFragment");
                } else {
                    fragmentTransaction.show(homeFragment);
                }
                break;
            case 1:
                if (deviceFragment == null) {
                    deviceFragment = new DeviceNewFragment();
                    fragmentTransaction.add(R.id.main_fragment_container, deviceFragment, "deviceFragment");
                } else {
                    fragmentTransaction.show(deviceFragment);
                }
                break;
            case 2:

                if (thirdFragment == null) {
                    thirdFragment = new ThirdFragment();
                    fragmentTransaction.add(R.id.main_fragment_container, thirdFragment, "thirdFragment");
                } else {
                    fragmentTransaction.show(thirdFragment);
                }
//                if (chartTwoFragment == null) {
//                    chartTwoFragment = new ChartTwoFragment();
//                    fragmentTransaction.add(R.id.main_fragment_container, chartTwoFragment, "chartFragment");
//                } else {
//                    fragmentTransaction.show(chartTwoFragment);
//                }
//                if (chartFragment == null) {
//                    chartFragment = new ChartFragment();
//                    fragmentTransaction.add(R.id.main_fragment_container, chartFragment);
//                } else {
//                    fragmentTransaction.show(chartFragment);
//                }
                break;
            case 3:
                if (orderFragment == null) {
                    orderFragment = new OrderFragment();
                    fragmentTransaction.add(R.id.main_fragment_container, orderFragment, "orderFragment");
                } else {
                    fragmentTransaction.show(orderFragment);
                }
//                if (userFragment == null) {
//                    userFragment = new UserFragment();
//                    fragmentTransaction.add(R.id.main_fragment_container, userFragment, "userFragment");
//                } else {
//                    fragmentTransaction.show(userFragment);
//                }
                break;
        }
        fragmentTransaction.commitAllowingStateLoss();

    }

    /**
     * 用来隐藏fragment的方法
     *
     * @param fragmentTransaction
     */
    private void hideFragment(FragmentTransaction fragmentTransaction) {
        //如果此fragment不为空的话就隐藏起来
        if (homeFragment != null) {
            fragmentTransaction.hide(homeFragment);
        }
        if (deviceFragment != null) {
            fragmentTransaction.hide(deviceFragment);
        }

        if (thirdFragment != null) {
            fragmentTransaction.hide(thirdFragment);
        }
//        if (chartTwoFragment != null) {
//            fragmentTransaction.hide(chartTwoFragment);
//        }
//        if (chartFragment != null) {
//            fragmentTransaction.hide(chartFragment);
//        }
        if (orderFragment != null) {
            fragmentTransaction.hide(orderFragment);
        }
    }


    /**
     * @param indexOfChild 需要变更为红色的view对应的索引位置
     */
    private void changUi(int indexOfChild) {
        int childCount = mainBottomeSwitcherContainer.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = mainBottomeSwitcherContainer.getChildAt(i);
            if (i == indexOfChild) {
                //选中条目变红,控件不可用
                setEnable(childView, false);
                tvTitle.setText(titles[i]);
                if (MyApplication.isConnected && i == 2) {
                    tvTitle.setText(getResources().getString(R.string.main_bluetooth_use_time) + " : " + MyApplication.limitSeconds / 60
                            + " " + getResources().getString(R.string.main_bluetooth_second));
                }
                if (i == 3) {
                    tvTitle.setText(getResources().getString(R.string.feedback));
                    tvTitle.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            final Intent intent = new Intent(MainActivity.this, FeedbackActivity.class);
                            startActivity(intent);
                            //  Toast.makeText(MainActivity.this,"点击",Toast.LENGTH_SHORT).show();

                        }
                    });
                } else {
                    tvTitle.setOnClickListener(null);
                }
            } else {
                setEnable(childView, true);
            }
        }
    }

    /**
     * @param childView
     * @param b
     */
    private void setEnable(View childView, boolean b) {
        if (childView instanceof ViewGroup) {
            //获取childView中的孩子结点(设置 ImageView + textView)--
            int childCount = ((ViewGroup) childView).getChildCount();
            for (int i = 0; i < childCount; i++) {
                View view = ((ViewGroup) childView).getChildAt(i);
                view.setEnabled(b);
                Log.i("mask", "setEnable: " + i);
            }
        }
    }

    @OnClick(R.id.ib_menu)
    public void onViewClicked() {
        InstructionsActivity.startAct(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (MySpUtils.getBoolean(MySpUtils.KEY_END_COURSE_TEST, false)) {
            Utils.EndCourse();
        }
    }
}
